import {computed, defineComponent, toRefs} from "vue";
import {Delete, Plus} from "@element-plus/icons-vue";

export default defineComponent({
  name: "EditableWrap",
  props: {
    fields: Array,
    modelValue: Array,
    readonly: Boolean,
    disabled: Boolean,
  },
  emits: ['update:modelValue'],
  setup(props, {slots, emit}) {
    const {readonly, modelValue,disabled} = toRefs(props)
    disabled.value=false
    const arr = computed({
      set: (val) => {
        emit('update:modelValue', val)
      },
      get: () => modelValue.value || []
    })
    const onClick = () => {
      const tmp = arr.value
      tmp.push({})
      arr.value = tmp
    }
    const onDel = (i) => {
      const tmp = arr.value
      tmp.splice(i, 1)
      arr.value = tmp
    }
    return () => (
        <>
          {arr.value.map((item, i) => {
            return <div style={{marginBottom: '10px', width: '100%', display: 'flex', columnGap: '5px'}}>
              {slots.default(item)}
              {
                !readonly.value &&
                <el-button type="warning" size="small" disabled={disabled.value} onClick={() => onDel(i)} circle icon={Delete}/>
              }
            </div>
          })}
          {
            !readonly.value && <el-button type="primary" disabled={disabled.value} onClick={onClick} circle icon={Plus}/>
          }
        </>
    )
  }
})
